package com.atguigu.tingshu.account.receiver;

import cn.hutool.core.collection.CollectionUtil;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.PipedReader;
import java.util.Map;

/**
 * @author: atguigu
 * @create: 2024-11-26 14:15
 */
@Slf4j
@Component
public class accountReceiver {

    @Autowired
    private UserAccountService userAccountService;


    /**
     * 用户首次登录平台，监听到消息后，初始化账户（余额）
     *
     * @param mqData  MQ消息对象 必须实现Serializable接口
     * @param message 消息对象
     * @param channel 通道对象
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_USER, durable = "true"),
            value = @Queue(value = MqConst.QUEUE_USER_REGISTER, durable = "true"),
            key = {MqConst.ROUTING_USER_REGISTER}
    ))
    public void initUserAccount(Map<String, Object> mqData, Message message, Channel channel) {
        if (CollectionUtil.isNotEmpty(mqData)) {
            log.info("[账户服务]监听到初始化账号消息：{}", mqData);
            //1.执行保存账户业务逻辑
            userAccountService.saveUserAccount(mqData);
        }
        //2.手动ack RabbitMQ收到消费者手动应答结构后，才会删除消息
        // 参数1：当前消息的tag值，每个消息增量+1数值  参数2：是否批量应答消息
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

}
